<template>
  <div class="nav-group">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true">
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增分组</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table v-loading="loading" :data="tableData" border stripe>
        <el-table-column label="图标" width="70" align="center">
          <template #default="{ row }">
            <span v-if="row.groupIcon" v-html="row.groupIcon" class="svg-icon"></span>
          </template>
        </el-table-column>
        <el-table-column prop="groupName" label="分组名称" />
        <el-table-column prop="groupOrder" label="排序" width="80" />
        <el-table-column prop="groupStatus" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.groupStatus === 1 ? 'success' : 'danger'">
              {{ row.groupStatus === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      append-to-body
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="groupName">
          <el-input v-model="form.groupName" placeholder="请输入分组名称" />
        </el-form-item>
        <el-form-item label="图标" prop="groupIcon">
          <el-input
            v-model="form.groupIcon"
            type="textarea"
            :rows="3"
            placeholder="请输入SVG图标代码"
          />
          <div class="icon-preview" v-if="form.groupIcon">
            <span>图标预览：</span>
            <span v-html="form.groupIcon" class="svg-icon"></span>
          </div>
        </el-form-item>
        <el-form-item label="排序" prop="groupOrder">
          <el-input-number v-model="form.groupOrder" :min="0" :max="99" />
        </el-form-item>
        <el-form-item label="状态" prop="groupStatus">
          <el-radio-group v-model="form.groupStatus">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { request } from '@/utils/request'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import { validateSvg } from '@/utils/svgValidator'
import { sanitizeSvg } from '@/utils/xssFilter'

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const form = ref({
  groupName: '',
  groupIcon: '',
  groupOrder: 5,
  groupStatus: 1
})

// 自定义 SVG 验证规则
const validateIcon = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入SVG图标代码'))
  } else if (!validateSvg(value)) {
    callback(new Error('请输入有效的SVG图标代码'))
  } else {
    callback()
  }
}

// 修改表单校验规则
const rules = {
  groupName: [
    { required: true, message: '请输入分组名称', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  groupIcon: [
    { required: true, message: '请输入SVG图标代码', trigger: 'blur' },
    { validator: validateIcon, trigger: 'blur' }
  ],
  groupOrder: [
    { required: true, message: '请输入排序号', trigger: 'blur' }
  ],
  groupStatus: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 重置表单
const resetForm = () => {
  form.value = {
    groupName: '',
    groupIcon: '',
    groupOrder: 5,
    groupStatus: 1
  }
}

// 获取分组列表
const getList = async () => {
  loading.value = true
  try {
    const res = await request('/api/nav/group/list', {
      method: 'GET'
    })
    if (res.code === 200) {
      tableData.value = res.data
    } else {
      ElMessage.error(res.msg || '获取分组列表失败')
    }
  } catch (error) {
    console.error('获取分组列表失败:', error)
    ElMessage.error('获取分组列表失败')
  } finally {
    loading.value = false
  }
}

// 新增
const handleAdd = () => {
  resetForm()
  dialogTitle.value = '新增分组'
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑分组'
  form.value = { ...row }
  dialogVisible.value = true
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该分组吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      const res = await request(`/api/nav/group/delete?id=${row.id}`, {
        method: 'GET'
      })
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getList()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 清理 SVG 代码
    const formData = { ...form.value }
    formData.groupIcon = sanitizeSvg(formData.groupIcon)
    
    const url = formData.id ? '/api/nav/group/update' : '/api/nav/group/add'
    const res = await request(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(formData)
    })
    
    if (res.code === 200) {
      ElMessage.success(formData.id ? '修改成功' : '新增成功')
      dialogVisible.value = false
      getList()
    } else {
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败')
  }
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style scoped>
.nav-group {
  padding: 20px;
}
.search-card {
  margin-bottom: 20px;
}
.table-card {
  margin-bottom: 20px;
}

.icon-preview {
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.svg-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.svg-icon :deep(svg) {
  width: 1em;
  height: 1em;
  font-size: 20px;
}
</style> 